unit editbuttons;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
  ExtCtrls, Buttons;

type

  { TEditButtonForm }

  TEditButtonForm = class ( TForm )
    AddItemEdit: TEdit;
    BitBtn1: TBitBtn;
    BitBtn2: TBitBtn;
    Label1: TLabel;
    ButtonPanel: TPanel;
    AutocompleteList: TListBox;
    ItemLabel: TLabel;
    VisibleCheckBox: TCheckBox;
    AutoCompleteIndex: TStringList;
    procedure AddItemEditChange ( Sender: TObject ) ;
    procedure AutocompleteListKeyDown ( Sender: TObject; var Key: Word;
      Shift: TShiftState ) ;
    procedure AutocompleteListMouseDown ( Sender: TObject;
      Button: TMouseButton; Shift: TShiftState; X, Y: Integer ) ;
    procedure FormCreate ( Sender: TObject ) ;
  private
    { private declarations }
  public
    { public declarations }
  end;

var
  EditButtonForm: TEditButtonForm;

implementation

uses main, db;

{$R *.lfm}

{ TEditButtonForm }

procedure TEditButtonForm.AddItemEditChange ( Sender: TObject ) ;
var
//  DB: TSQLiteTable;
  r : integer;
  query: String;
begin
  if Length(AddItemEdit.Text) > 4 then
    begin
      //DB := TSQLiteTable.Create(Application);
      AutoCompleteIndex.Clear;
      AutoCompleteList.Clear;
      AutoCompleteList.Visible := True;
      try
        MainDB.SQL := 'SELECT name, barcode FROM products'
                                 + ' WHERE barcode LIKE "' + AddItemEdit.Text + '%"'
                                 + ' OR name LIKE "%' + AddItemEdit.Text + '%"'
                                 + ' ORDER BY name;';
        MainDB.Open;
        if MainDB.State=dsBrowse then
        while not MainDB.EOF do
          begin
    //        test2 :=DB.Fields[0].AsString;
            AutoCompleteList.items.Add( MainDB.Fields[0].AsString );
            AutoCompleteIndex.Add( MainDB.Fields[1].AsString );
            MainDB.Next;
          end;
      finally
        MainDB.Close;
      end;
    end;
end;

procedure TEditButtonForm.AutocompleteListKeyDown ( Sender: TObject;
  var Key: Word; Shift: TShiftState ) ;
begin
  if Key=27 then
     begin
       AutoCompleteList.Visible := false;
       AutoCompleteList.Clear;
       AddItemEdit.SetFocus;
     end
  else if Key=13
            then AutoCompleteListMouseDown(nil, mbLeft, [],0,0);
end;

procedure TEditButtonForm.AutocompleteListMouseDown ( Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer ) ;
var
  i: LongInt;
begin
  i := AutoCompleteList.ItemIndex;
  ItemLabel.Caption := AutoCompleteList.Items[i];
  AddItemEdit.Text := AutoCompleteIndex.Strings[i];

  AutoCompleteList.Visible := false;
end;

procedure TEditButtonForm.FormCreate ( Sender: TObject ) ;
begin
  AutoCompleteIndex := TStringList.Create;
end;

end.

